package com.sysu.simulation.widget;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sysu.simulation.ClothesActivity;
import com.sysu.simulation.R;
import com.sysu.simulation.adapter.BaseRecyclerAdapter;
import com.sysu.simulation.adapter.ClothesListAdapter;
import com.sysu.simulation.bean.Clothes;
import com.sysu.simulation.bean.ListResult;
import com.sysu.simulation.helper.ApiHelper;
import com.sysu.simulation.helper.NetworkHelper;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import cz.msebera.android.httpclient.Header;

public class ClothesListFragment extends BaseRecyclerFragment<Clothes>{
    private String uid;
    private static final String CLOTHES_KEY_NAME = "clothes";
    private static final String BUNDLE_USER_ID = "bundle_user_id";
    private boolean isMultiMode = false;
    private ClothesListAdapter clothesListAdapter;
    private FloatingActionButton mFab;
    private OnClothesListClickListener mListener;

    public static ClothesListFragment newInstance() {
        return new ClothesListFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnClothesListClickListener) {
            mListener = (OnClothesListClickListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnClothesListClickListener");
        }
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mFab = (FloatingActionButton) root.findViewById(R.id.fab_add);
        mFab.show();
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mListener!=null)
                    mListener.onFloatingButtonClick();
            }
        });

        clothesListAdapter = (ClothesListAdapter)mAdapter;
    }

    @Override
    protected void initData() {
        setCache(true);
        super.initData();
    }

    @Override
    protected void initBundle(Bundle bundle) {
        super.initBundle(bundle);
        uid = bundle.getString(BUNDLE_USER_ID);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    @Override
    protected void requestData() {
        super.requestData();
        if(NetworkHelper.hasInternet(mContext)) {
            ApiHelper.getUserClothes(uid, mDatas.getNextItem(), mHandler);
        }
        else {
            Toast.makeText(mContext,"未连接网络",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected Type getResultType() {
        return new TypeToken<ListResult<Clothes>>(){}.getType();
    }

    @Override
    protected Type getCacheType() {
        return new TypeToken<List<Clothes>>(){}.getType();
    }

    @Override
    protected String getCacheKeyName() {
        return CLOTHES_KEY_NAME;
    }

    @Override
    protected void onItemClick(Clothes item, int position) {
        if(!isMultiMode) {
            mListener.onClothesItemClick(item, position);
        }
        else {
            clothesListAdapter.addOrRemove(position);
        }
    }

    @Override
    protected void onItemLongClick(Clothes item, int position) {
        if(!isMultiMode) {
            ((ClothesActivity)getActivity()).startMultiMode();
            setMultiMode(true);
            clothesListAdapter.addOrRemove(position);
        }
    }

    @Override
    protected BaseRecyclerAdapter<Clothes> getAdapter() {
        return new ClothesListAdapter(mContext);
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mContext);
    }

    public void setMultiMode(boolean isMulti) {
        isMultiMode = isMulti;
        //clothesListAdapter.getSelectedSet().clear();
        if(isMulti) mFab.hide();
        else mFab.show();
        clothesListAdapter.showMultiBox(isMultiMode);
    }

    public void deleteItems() {
        List<String> all_clothes = new LinkedList<>();
        SparseBooleanArray sp = clothesListAdapter.getSelectedSet();
        final int oldToken = mDatas.getNextItem();
        int removedBeforeNextItem = 0;

        for(int i=0; i<sp.size(); i++) {
            if(sp.valueAt(i)) {
                String clothes_name = clothesListAdapter.getItem(sp.keyAt(i)).getTitle();
                all_clothes.add(clothes_name);
                if(sp.keyAt(i) < oldToken) removedBeforeNextItem++;
            }
        }
        final int newToken = oldToken - removedBeforeNextItem;

        ApiHelper.deleteUserClothes(uid, all_clothes, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Toast.makeText(mContext, "网络请求错误，请重试。", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(responseString.equals("-1"))
                    Toast.makeText(mContext, "删除失败，请重试。", Toast.LENGTH_SHORT).show();
                else {
                    mDatas.setNextItem(newToken);
                    onDeleteComplete();
                }
            }
        });
    }

    private void onDeleteComplete() {
        clothesListAdapter.removeSelectedItems();
    }

    public void onClothesAdded(Clothes clothes) {
        mAdapter.addItem(clothes);
    }

    public void onClothesEdited(Clothes clothes, int position) {
        mAdapter.setItem(position, clothes);
    }

    public interface OnClothesListClickListener {
        void onFloatingButtonClick();
        void onClothesItemClick(Clothes item, int position);
    }
}
